﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Web.Http;
using System.Web.Http.Results;
using Common;

namespace WebApi
{

    public class ContactsController : BaseController
    {
        private static List<Contact> Contacts=new List<Contact>();
        private static int counts = 2;

        static ContactsController()
        {
            Contacts.Add(new Contact()
            {
                Id = "2",
                Name = "kevin",
                PhoneNo = "2132312",
                EmailAddress = "dhsadh@12.com",
                Address = "测试地址你猜猜"
            });
            Contacts.Add(new Contact()
            {
                Id = "1",
                Name = "lily",
                PhoneNo = "26484325",
                EmailAddress = "d3434dh@1sda.com",
                Address = "上海徐家汇"
            });
            Contacts.Add(new Contact()
            {
                Id = "3",
                Name = "mary",
                PhoneNo = "125689123",
                EmailAddress = "ewarfds@sina.com",
                Address = "上海南翔镇真南路236号"
            });
        }
       [HttpGet]
        public HttpResponseMessage Get(string id = null)
        {
           var list= from contact in Contacts
            where contact.Id == id || string.IsNullOrEmpty(id)
            select contact;
     
            return Common.GetInstince().ToJsonResult(list.OrderBy(m=>m.Id));
        }

        [HttpPost]
        public void Post(Contact contact)
        {
            Interlocked.Increment(ref counts);
            contact.Id = counts.ToString("D3");
            //contact.Name = "3dassad";
            //contact.Address = "地址3";
            Contacts.Add(contact);

        }

        [HttpPut]
        public void Put(Contact contact)
        {

            Contacts.Remove(Contacts.First(m => m.Id == contact.Id));
            Contacts.Add(contact);
        }

        [HttpDelete]
        public IEnumerable<Contact> Delete(string id)
        {
            Contacts.Remove(Contacts.First(m => m.Id == id));
            return Contacts;

        }


       //http://www.cnblogs.com/zhili/p/AngularJSPrivilege.html
    }
}
